package com.ffs.persist.utils;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtobufIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

/**
 * 序列化工具
 *
 * @author ffs80
 */
public class SerializerUtil {

    /**
     * 序列化
     */
    public static <T> byte[] encode(T object, Class<T> clazz) {
        Schema<T> schema = RuntimeSchema.getSchema(clazz);
        LinkedBuffer buffer = LinkedBuffer.allocate();
        return ProtobufIOUtil.toByteArray(object, schema, buffer);
    }

    /**
     * 反序列化
     */
    public static <T> T decode(byte[] bytes, Class<T> clazz) {
        T object;
        try {
            object = clazz.newInstance();
        } catch (Exception e) {
            return null;
        }

        return decode(bytes, clazz, object);
    }

    private static <T> T decode(byte[] bytes, Class<T> clazz, T object) {
        Schema<T> schema = RuntimeSchema.getSchema(clazz);
        ProtobufIOUtil.mergeFrom(bytes, object, schema);
        return object;
    }
}
